import time
from threading import Thread
from multiprocessing import Process, Pool as ProcessPool, cpu_count
from multiprocessing.dummy import Pool as ThreadPool


def count_time(func):
    """
    计时装饰器
    :param func:
    :return:
    """

    def inner(num):
        start = time.time()
        func(num)
        end = time.time()
        print("耗时：%f" % (end - start))

    return inner


@count_time
def normal_time(num):
    """
    普通方法
    :param num:
    :return:
    """
    for i in range(num):
        sum(range(1, 1000000, 2))


def tmp_time(total):
    sum(range(1, total, 2))


@count_time
def thread_time(num):
    """
    使用多线程
    :param num:
    :return:
    """
    for i in range(num):
        thread = Thread(target=tmp_time)
        thread.start()
        thread.join()


@count_time
def process_time(num):
    """
    使用多进程
    :param num:
    :return:
    """
    for i in range(num):
        process = Process(target=tmp_time)
        process.start()
        process.join()


@count_time
def threadpool_time(num):
    """
    使用线程池
    :param num:
    :return:
    """
    for i in range(num):
        thread_pool = ThreadPool(cpu_count())
        thread_pool.apply_async(tmp_time)
        thread_pool.close()
        thread_pool.join()


@count_time
def processpool_time(num):
    """
    使用进程池
    :param num:
    :return:
    """
    for i in range(num):
        process_pool = ProcessPool(cpu_count())
        process_pool.apply_async(tmp_time)
        process_pool.close()
        process_pool.join()


if __name__ == "__main__":
    normal_time(10)
    thread_time(10)
    process_time(10)
    threadpool_time(10)
    processpool_time(10)
